package com.ayoka.ui.launch;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Paint;
import android.os.Bundle;
import android.view.View;
import android.view.WindowManager;
import android.widget.CompoundButton;

import com.ayoka.Constant;
import com.ayoka.R;
import com.ayoka.base.BaseActivity;
import com.ayoka.bean.UserInformation;
import com.ayoka.databinding.ActivityLaunchBinding;
import com.ayoka.mvp.LaunchMVP.ILaunchView;
import com.ayoka.mvp.LaunchMVP.LaunchPresenter;
import com.ayoka.ui.html5.SimpleHtml5WebViewActivity;
import com.ayoka.ui.main.MainActivity;
import com.ayoka.utils.WeChatManager;
import com.jcp.baselibrary.base.APPActivityManager;
import com.jcp.baselibrary.dialog.DialogHelper;
import com.jcp.baselibrary.model.ToolBarOptions;
import com.jcp.baselibrary.utils.SPUtil;
import com.jcp.baselibrary.utils.TDevice;
import com.jcp.baselibrary.utils.UIUtils;
import com.jincp.image.load.ImageLoaderProxy;

import java.util.Observable;


/**
 * =========================================================
 *
 * @ProjectName:
 * @ClassName: LaunchActivity
 * @Description: 启动activity
 * @Author: jincp
 * @CreateDate: 2019/3/14 12:55
 * =========================================================
 */
public class LaunchActivity extends BaseActivity<ActivityLaunchBinding, LaunchPresenter> implements ILaunchView {

    public static void start(Activity activity) {
        APPActivityManager.getInstance().finishAll();
        Intent intent = new Intent(activity, LaunchActivity.class);
        intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
        activity.startActivity(intent);
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        initViews();
    }

    @Override
    protected void onBeforeSetContentLayout() {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
    }

    @Override
    public int getContentLayout() {
        return R.layout.activity_launch;
    }

    @Override
    protected void initViews() {
        mDataBinding.btnWxLogin.setOnClickListener(this);
        mDataBinding.tvServiceAgreement.setOnClickListener(this);
        mDataBinding.tvServiceAgreement.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
        mDataBinding.cbNext.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                mDataBinding.btnWxLogin.setEnabled(isChecked);
            }
        });

        configLoginButton();
    }

    private void configLoginButton() {
        if (UserInformation.getInstance() != null) {
            mDataBinding.llLogin.setVisibility(View.GONE);
            mDataBinding.llBottom.setVisibility(View.VISIBLE);
        } else {
            int versionCode = SPUtil.getInt(Constant.APP_LOCAL_VERSION, 0);
            // 判断本地存储的version 和 app的version 是否一致
            if (versionCode == TDevice.getVersionCode()) {
                mDataBinding.llLogin.setVisibility(View.VISIBLE);
                mDataBinding.llBottom.setVisibility(View.GONE);
            } else {
                ImageLoaderProxy.getInstance().cleanCache();
                mDataBinding.llLogin.setVisibility(View.GONE);
                mDataBinding.llBottom.setVisibility(View.VISIBLE);
            }
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
        if (UserInformation.getInstance() != null) {
            mPresenter.refreshToken();
        } else {
            UIUtils.postTaskDelay(task, 3000);
        }
    }

    private Runnable task = new Runnable() {
        @Override
        public void run() {
            if (UserInformation.getInstance() != null) {
                MainActivity.start(LaunchActivity.this);
                finish();
            } else {
                try {
                    int versionCode = SPUtil.getInt(Constant.APP_LOCAL_VERSION, 0);
                    if (versionCode < TDevice.getVersionCode()) {
                        SPUtil.putInt(Constant.APP_LOCAL_VERSION, TDevice.getVersionCode());
                        ImageLoaderProxy.getInstance().cleanCache();
                        JoinActivity.start(LaunchActivity.this);
                        finish();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    };

    @Override
    protected LaunchPresenter getPresenter() {
        return new LaunchPresenter();
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (view == mDataBinding.tvServiceAgreement) {
            ToolBarOptions options = new ToolBarOptions("用户注册协议");
            SimpleHtml5WebViewActivity.start(this, Constant.SERVICE_AGREEMENT_URL, "", options);
        }
        if (view == mDataBinding.btnWxLogin) {
            WeChatManager.getInstance().addObserver(this);
            WeChatManager.getInstance().startLogin();
            mDataBinding.btnWxLogin.setEnabled(false);
        }
    }

    @Override
    public void onLoginCallback(boolean isSuccess) {
        if (isSuccess) {
            showToast(getString(R.string.wechat_login_success));
            MainActivity.start(LaunchActivity.this);
            finish();
        } else {
            showToast(getString(R.string.wechat_login_failure));
            mDataBinding.btnWxLogin.setEnabled(true);
        }
    }

    @Override
    public void onRefreshTokenCallback(boolean isSuccess) {
        if (isSuccess) {
            MainActivity.start(LaunchActivity.this);
            finish();
        } else {
            DialogHelper.getOkDialog(this, "登录过期，需要重新登录!").show();
            UserInformation.setUserInformation(null);
            mDataBinding.llLogin.setVisibility(View.VISIBLE);
            mDataBinding.llBottom.setVisibility(View.GONE);
        }
    }


    @Override
    public void update(Observable observable, Object data) {
        super.update(observable, data);
        if (observable instanceof WeChatManager) {
            int operation = (int) data;
            if (WeChatManager.WE_CHAT_LOGIN_START == operation) {
                showWaitDialog(getString(R.string.wechat_login_start));
            } else if (WeChatManager.WE_CHAT_LOGIN_SUCCESS == operation) {
                String openId = SPUtil.getString(Constant.WX_OPEN_ID, "");
                mPresenter.loginByWechat(openId);
            } else if (WeChatManager.WE_CHAT_LOGIN_FILED == operation) {
                showToast(getString(R.string.wechat_login_failure));
                mDataBinding.btnWxLogin.setEnabled(true);
                hideWaitDialog();
            } else if (WeChatManager.WE_CHAT_LOGIN_CANCEL == operation) {
                showToast(getString(R.string.user_cancel_login));
                mDataBinding.btnWxLogin.setEnabled(true);
                hideWaitDialog();
            }
        }
    }

    @Override
    protected void onDestroy() {
        WeChatManager.getInstance().deleteObserver(this);
        super.onDestroy();
    }
}
